package com.ruoyi.inducePest.service.inducePest.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ListObjectsV2Request;
import com.aliyun.oss.model.ListObjectsV2Result;
import com.aliyun.oss.model.OSSObjectSummary;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.inducePest.domain.ChangeRecord;
import com.ruoyi.inducePest.domain.InduceDetectionLog;
import com.ruoyi.inducePest.domain.Rect;
import com.ruoyi.inducePest.domain.device.InduceDeviceInfo;
import com.ruoyi.inducePest.domain.device.Lure;
import com.ruoyi.inducePest.domain.inducePest.BeginTimeAndEndTimt;
import com.ruoyi.inducePest.domain.inducePest.InducePestImgInfo;
import com.ruoyi.inducePest.domain.inducePest.InducePestNumType;
import com.ruoyi.inducePest.domain.inducePest.SelectInducePestImgInfo;
import com.ruoyi.inducePest.mapper.ChangeRecordMapper;
import com.ruoyi.inducePest.mapper.device.InduceDeviceMapper;
import com.ruoyi.inducePest.mapper.inducePest.InducePestImgMapper;
import com.ruoyi.inducePest.service.device.InduceDeviceService;
import com.ruoyi.inducePest.service.inducePest.InducePestCaptureImgService;
import com.ruoyi.inducePest.service.inducePest.InducePestDataAnalysisService;
import com.ruoyi.permission.Dao.SerDevicePermi;
import com.ruoyi.permission.mapper.SerDevicePermiMapper;
import com.ruoyi.traplight.domain.BufferedImageMultipartFile;
import com.ruoyi.utils.*;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * * @author LiSuxuan
 * * @date 2022年 01月 09日 13:08
 * * 从海康ISC平台上获取图片
 */
@Slf4j
@Service
public class InducePestCaptureImgServiceImpl implements InducePestCaptureImgService {

    @Autowired
    private InducePestImgMapper inducePestImgMapper;

    @Autowired
    private InduceDeviceMapper induceDeviceMapper;

    @Autowired
    private SerDevicePermiMapper devicePermiMapper;

    @Autowired
    private ChangeRecordMapper changeRecordMapper;

    @Autowired
    private InduceDeviceService induceDeviceService;

    @Autowired
    private InducePestDataAnalysisService inducePestDataAnalysisService;

    /**
     * 能力开放平台的网站路径
     */
    private static final String ARTEMIS_PATH = "/artemis";

    /**
     * 模型检测图像处理路径
     */
    @Value("${ruoyi.detectionIndecumentCADUrl}")
    private String detectionUrl;



    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 害虫最大数量
     * 当图中虫数大于该数值后，
     */
    private int maxPestNumber=100;

    /**
     * 阿里云OSS相关参数
     */
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private String accessKeyId = "LTAI5t7oAKmJTadnQpVt8ei2";
    private String accessKeySecret = "GzNTOPwtu2g9gkZuCPc4K0BZAXxJiX";
    // 填写Bucket名称，例如examplebucket。
    private String bucketName = "xy-capture-image";

    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * @param inducePestImgInfo
     * @return
     */
    @Override
    public TableDataInfo getInfoByCondition(SelectInducePestImgInfo inducePestImgInfo, Integer pageNum, Integer pageSize) throws JsonProcessingException {
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<InducePestImgInfo> inducePestImgInfos = inducePestImgMapper.getInfoByCondition(inducePestImgInfo);

        PageInfo<InducePestImgInfo> pageInfo = new PageInfo<>(inducePestImgInfos);
        return getTableDataInfo(inducePestImgInfos,pageInfo);

    }

    @Override
    public List<String> getPestTypeInfoByCondition(SelectInducePestImgInfo inducePestImgInfo) {

        List<String> pestTypes = inducePestImgMapper.selectImgPestByDeviceId(inducePestImgInfo);

        List<String> newImgPestType = new ArrayList<String>();
        for (String str : pestTypes) {
            if (!newImgPestType.contains(str)) {
                newImgPestType.add(str);
            }
        }
        return newImgPestType;
    }


    public void draw(String tag, String imgPath,String corner,String imgPest) {
        ImgDrawCircleTool tool = new ImgDrawCircleTool();
        String[] corners = corner.split(",");
        List<int[]> list = new ArrayList<>();
        for(int i=0;i<corners.length;i=i+4){
            int[] cornerArray= new int[]{Integer.parseInt(corners[i]), Integer.parseInt(corners[i + 1]), Integer.parseInt(corners[i + 2]), Integer.parseInt(corners[i + 3])};
            list.add(cornerArray);
        }
        List<String> tagList = com.alibaba.fastjson2.JSON.parseArray(tag, String.class);
        tool.doDrawRectangle(list, tagList, profile + imgPath,imgPest);
    }

    private TableDataInfo getTableDataInfo(List<InducePestImgInfo> inducePestImgInfos, PageInfo<InducePestImgInfo> pageInfo) throws JsonProcessingException {
        ArrayList<InducePestImgInfo> returnInducePestImgInfos = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        for (InducePestImgInfo inducePestImgInfo : inducePestImgInfos) {
            InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
            induceDeviceInfo.setId(inducePestImgInfo.getDeviceId());
            List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);
            if(induceDeviceInfos.size()!=0){
                inducePestImgInfo.setDeviceName(induceDeviceInfos.get(0).getName());
            }


            Lure lure = new Lure();
            lure.setCanModel(1);
            List<Lure> lures = induceDeviceService.selectLure(lure);
            // 提取lure字段生成新的List
            List<String> induceModelPestList = lures.stream()
                    .map(Lure::getLure)
                    .collect(Collectors.toList());



            if(inducePestImgInfo.getTagManual()==null || inducePestImgInfo.getTagManual().equals("")){
                inducePestImgInfo.setTagCount(0);
                inducePestImgInfo.setTagOtherCount(0);
            }else if(induceModelPestList.contains(inducePestImgInfo.getImgPest())){
                // 获取指定害虫的数量
                Map<String, Integer> insectMap = objectMapper.readValue(inducePestImgInfo.getTagManual(), new TypeReference<Map<String, Integer>>() {});
                String pinYinImgPest = getPinYinHeadChar(inducePestImgInfo.getImgPest());
                int quantity = insectMap.get(pinYinImgPest)==null?0:insectMap.get(pinYinImgPest);
                inducePestImgInfo.setTagCount(quantity);
                inducePestImgInfo.setTagOtherCount(getMapAllSum(insectMap)-quantity);
            }else {

                Map<String, Integer> insectMap = objectMapper.readValue(inducePestImgInfo.getTagManual(), new TypeReference<Map<String, Integer>>() {});
                inducePestImgInfo.setTagCount(getMapAllSum(insectMap));
                inducePestImgInfo.setTagOtherCount(0);
            }


            //根据图片是否是新板判断新增
            if(inducePestImgInfo.getIsNewBoard()==1){
                inducePestImgInfo.setTagNewCount(inducePestImgInfo.getTagCount());
            }else {
                InducePestImgInfo yesterdayInducePestImgInfo = inducePestDataAnalysisService.selectLastInsectInfoByDay(inducePestImgInfo.getCaptureTime(), inducePestImgInfo.getDeviceId());
                if (yesterdayInducePestImgInfo!=null ) {
                    Integer mapAllSum=0;
                    if(yesterdayInducePestImgInfo.getTagManual()==null || yesterdayInducePestImgInfo.getTagManual().equals("")){
                        mapAllSum=0;
                    }else {
                        Map<String, Integer> insectYesterdayMap = objectMapper.readValue(yesterdayInducePestImgInfo.getTagManual(), new TypeReference<Map<String, Integer>>() {
                        });
                        mapAllSum = getMapAllSum(insectYesterdayMap);
                    }
                    int tagNewCount=inducePestImgInfo.getTagCount()-mapAllSum;
                    if(tagNewCount<0){
                        tagNewCount=0;
                    }
                    inducePestImgInfo.setTagNewCount(tagNewCount);
                }else {
                    inducePestImgInfo.setTagNewCount(inducePestImgInfo.getTagCount());
                }

            }


            inducePestImgInfo.setPhotoName(inducePestImgInfo.getImageName());
            inducePestImgInfo.setPhotoTime(inducePestImgInfo.getCaptureTime());
            inducePestImgInfo.setPhotoUpdateTime(inducePestImgInfo.getCaptureTime());
            inducePestImgInfo.setResultPath(inducePestImgInfo.getResultUrl());
            inducePestImgInfo.setThumbPath(inducePestImgInfo.getThumUrl());
            inducePestImgInfo.setPhotoPath(inducePestImgInfo.getUrl());
            inducePestImgInfo.setModel(true);




            returnInducePestImgInfos.add(inducePestImgInfo);

        }


        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(returnInducePestImgInfos);
        rspData.setTotal(pageInfo.getTotal());
        return rspData;
    }

    @Override
    public List<InduceDetectionLog> insertInfoForMultipartFile(MultipartFile[] files) throws ImageProcessingException, IOException, ParseException {
        List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();
        for(MultipartFile file:files) {
            InducePestImgInfo inducePestImgInfo = new InducePestImgInfo();
            inducePestImgInfo.setIsCaputreManual(1);
            Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
            Integer userId=Integer.valueOf(userIdL.intValue());
            inducePestImgInfo.setUserId(userId);
            List<InduceDetectionLog> InduceDetectionLogs = inducePestModelDetection(file, inducePestImgInfo);
            result.addAll(InduceDetectionLogs);
        }
        return result;

    }

    @Override
    public List<InduceDetectionLog> insertInfoForSingleDetail(MultipartFile file, InducePestImgInfo inducePestImgInfo) throws ImageProcessingException, IOException, ParseException {
        List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();
        inducePestImgInfo.setIsCaputreManual(1);

        List<InduceDetectionLog> InduceDetectionLogs = inducePestModelDetection(file, inducePestImgInfo);
        result.addAll(InduceDetectionLogs);
        return result;
    }

    /**
     * 从OSS拉取图片
     * @return
     */
    @Override
    public List<InduceDetectionLog> downImageFromOSSAuto() throws ParseException {
        // 创建OSSClient实例。
        //List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();

        Map<String, Integer> deviceImageNum = new HashMap<String, Integer>();
        List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();
        List<InduceDeviceInfo> induceDeviceInfosForCamera = induceDeviceMapper.selectAllDeviceInfo();
        for (InduceDeviceInfo induceDeviceInfo : induceDeviceInfosForCamera) {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            deviceImageNum.put(induceDeviceInfo.getCameraId(), 0);

            // 指定前缀，例如exampledir/object。
            String prefix = induceDeviceInfo.getCameraId()+"_";
            Calendar calendar = Calendar.getInstance();

            calendar.setTime(new Date());					//放入Date类型数据

            int year = calendar.get(Calendar.YEAR);//获取年份
            int month = calendar.get(Calendar.MONTH)+1;//获取月份
            int date = calendar.get(Calendar.DATE);//获取日

            String monthSt="";
            if(month<10){
                monthSt="0"+month;
            }else {
                monthSt=month+"";
            }
            String dateSt="";
            if(date<10){
                dateSt="0"+date;
            }else {
                dateSt=date+"";
            }
            String pathDay= year +"-"+ monthSt +"-"+ dateSt;
            prefix=prefix+pathDay;
            try {
                // 列举指定前缀的文件。
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
                listObjectsV2Request.setPrefix(prefix);
                ListObjectsV2Result listObjectsV2Result = ossClient.listObjectsV2(listObjectsV2Request);
                List<OSSObjectSummary> ossObjectSummaries = listObjectsV2Result.getObjectSummaries();

                for (OSSObjectSummary s : ossObjectSummaries) {
                    String objectName = s.getKey();

                    SelectInducePestImgInfo selectInducePestImgInfo = new SelectInducePestImgInfo();
                    calendar = Calendar.getInstance();
                    calendar.setTime(new Date());

                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    Date beginTime = calendar.getTime();
                    calendar.set(Calendar.HOUR_OF_DAY, 23);
                    calendar.set(Calendar.MINUTE, 59);
                    calendar.set(Calendar.SECOND, 59);
                    Date endTime = calendar.getTime();

                    selectInducePestImgInfo.setBeginTime(beginTime);
                    selectInducePestImgInfo.setEndTime(endTime);
                    boolean isHaveImage=false;  //判断数据库中是否有该图片了
                    for (InducePestImgInfo inducePestImgInfo : inducePestImgMapper.getInfoByCondition(selectInducePestImgInfo)) {
                        if(inducePestImgInfo.getImageName().equals(objectName)){
                            isHaveImage=true;
                            break;
                        }
                    }
                    if(isHaveImage){
                        continue;
                    }
                    String hoursMinuteSecond=objectName.split(pathDay)[1].replace("_","").split("\\.")[0];
                    String hours=hoursMinuteSecond.split("-")[0];
                    String minutes=hoursMinuteSecond.split("-")[1];
                    String seconds=hoursMinuteSecond.split("-")[2];
                    String imageTime=pathDay+" "+hours+":"+minutes+":"+seconds;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date captureDate = sdf.parse(imageTime);
                    String pathName = RuoYiConfig.getDetectionPath()+File.separator+objectName;
                    ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
                    InducePestImgInfo inducePestImgInfo = new InducePestImgInfo();
                    //Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
                    //Integer userId=Integer.valueOf(userIdL.intValue());

                    inducePestImgInfo.setCaptureTime(captureDate);
                    InduceDeviceInfo selectInduceDeviceInfo = new InduceDeviceInfo();
                    String cameraId=objectName.split("_"+pathDay)[0];
                    if(deviceImageNum.get(cameraId)==null){
                        deviceImageNum.put(cameraId, 0);
                    }
                    deviceImageNum.put(cameraId, deviceImageNum.get(cameraId)+1);
                    selectInduceDeviceInfo.setCameraId(cameraId);

                    List<InduceDeviceInfo> induceDeviceInfos = this.induceDeviceMapper.selectDeviceInfoByCondition(selectInduceDeviceInfo);
                    if(induceDeviceInfos.size()!=0){
                        inducePestImgInfo.setDeviceId(induceDeviceInfos.get(0).getId());
                        inducePestImgInfo.setUserId(induceDeviceInfos.get(0).getUserId());

                    }else {
                        selectInduceDeviceInfo.setName(cameraId);
                        induceDeviceMapper.insertDeviceInfo(selectInduceDeviceInfo);
                        inducePestImgInfo.setDeviceId(selectInduceDeviceInfo.getId());

                    }
                    inducePestImgInfo.setIsCaputreManual(0);

                    MultipartFile mFile = null;

                    try {
                        File file = new File(pathName);
                        FileInputStream fileInputStream = new FileInputStream(file);

                        String fileName = file.getName();
                        fileName = fileName.substring((fileName.lastIndexOf("/") + 1));
                        mFile =  new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

                        List<InduceDetectionLog> InduceDetectionLogs = inducePestModelDetection(mFile, inducePestImgInfo);
                        result.addAll(InduceDetectionLogs);
                        file.delete();
                    } catch (Exception e) {
                        log.error("封装文件出现错误：{}", e);
                        //e.printStackTrace();
                    }
                }
            }catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } catch (ParseException e) {
                e.printStackTrace();
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }


        for (String key : deviceImageNum.keySet()) {
            InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
            induceDeviceInfo.setCameraId(key);
            List<InduceDeviceInfo> induceDeviceInfos = this.induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);

            induceDeviceInfo.setId(induceDeviceInfos.get(0).getId());

            SelectInducePestImgInfo inducePestImgInfo = new SelectInducePestImgInfo();
            inducePestImgInfo.setDeviceId(induceDeviceInfo.getId());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date beginTime = calendar.getTime();
            calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            Date endTime = calendar.getTime();

            inducePestImgInfo.setBeginTime(beginTime);
            inducePestImgInfo.setEndTime(endTime);
            List<InducePestImgInfo> infoByCondition = inducePestImgMapper.getInfoByCondition(inducePestImgInfo);
            if(infoByCondition.size()>0){
                induceDeviceInfo.setStatus("在线");
            }else {
                induceDeviceInfo.setStatus("离线");
            }
            String onlineState = induceDeviceInfo.getStatus();
            Date date = new Date();
            // 创建SimpleDateFormat对象，指定字符串的日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 调用format() 方法，格式化时间，转换为指定格式字符串
            String now = sdf.format(date);
            Date updateTime = sdf.parse(now);
            String deviceName = induceDeviceInfos.get(0).getName();


            SerDevicePermi devicePermiInfo = devicePermiMapper.selectByDeviceSerial(induceDeviceInfo.getCameraId());
            devicePermiInfo.setOnlineState(onlineState);
            devicePermiInfo.setDeviceName(deviceName);
            devicePermiMapper.updateByPrimaryKeySelective(devicePermiInfo);
            this.induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);
        }

        return result;
    }

    @Override
    public List<InduceDetectionLog> downImageFromOSSAutoByTime(String beginDay,String endDay) throws ParseException {
        // 创建OSSClient实例。
        //List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();
        List<String> dates = MyDateUtil.calculateTimeInterval(beginDay, endDay);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, Integer> deviceImageNum = new HashMap<String, Integer>();
        List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();
        List<InduceDeviceInfo> induceDeviceInfosForCamera = induceDeviceMapper.selectAllDeviceInfo();
        for (InduceDeviceInfo induceDeviceInfo : induceDeviceInfosForCamera) {

            deviceImageNum.put(induceDeviceInfo.getCameraId(), 0);

            Calendar calendar = Calendar.getInstance();


            for (String newDate : dates) {
                // 指定前缀，例如exampledir/object。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                String prefix = induceDeviceInfo.getCameraId() + "_";
                prefix = prefix + newDate;
                try {
                    // 列举指定前缀的文件。
                    ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
                    listObjectsV2Request.setPrefix(prefix);
                    ListObjectsV2Result listObjectsV2Result = ossClient.listObjectsV2(listObjectsV2Request);
                    List<OSSObjectSummary> ossObjectSummaries = listObjectsV2Result.getObjectSummaries();

                    for (OSSObjectSummary s : ossObjectSummaries) {
                        String objectName = s.getKey();
                        SelectInducePestImgInfo selectInducePestImgInfo = new SelectInducePestImgInfo();
                        calendar = Calendar.getInstance();
                        calendar.setTime(new Date());
                        calendar.set(Calendar.HOUR_OF_DAY, 0);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                        Date beginTime = calendar.getTime();
                        calendar.set(Calendar.HOUR_OF_DAY, 23);
                        calendar.set(Calendar.MINUTE, 59);
                        calendar.set(Calendar.SECOND, 59);
                        Date endTime = calendar.getTime();

                        selectInducePestImgInfo.setBeginTime(beginTime);
                        selectInducePestImgInfo.setEndTime(endTime);
                        boolean isHaveImage = false;  //判断数据库中是否有该图片了
                        for (InducePestImgInfo inducePestImgInfo : inducePestImgMapper.getInfoByCondition(selectInducePestImgInfo)) {
                            if (inducePestImgInfo.getImageName().equals(objectName)) {
                                isHaveImage = true;
                                break;
                            }
                        }
                        if (isHaveImage) {
                            continue;
                        }
                        String hoursMinuteSecond = objectName.split(newDate)[1].replace("_", "").split("\\.")[0];
                        String hours = hoursMinuteSecond.split("-")[0];
                        String minutes = hoursMinuteSecond.split("-")[1];
                        String seconds = hoursMinuteSecond.split("-")[2];
                        String imageTime = newDate + " " + hours + ":" + minutes + ":" + seconds;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date captureDate = sdf.parse(imageTime);
                        String pathName = RuoYiConfig.getDetectionPath() + File.separator + objectName;
                        ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
                        InducePestImgInfo inducePestImgInfo = new InducePestImgInfo();
                        //Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
                        //Integer userId=Integer.valueOf(userIdL.intValue());
                        //inducePestImgInfo.setUserId(userId);
                        inducePestImgInfo.setCaptureTime(captureDate);
                        InduceDeviceInfo newInduceDeviceInfo = new InduceDeviceInfo();
                        String cameraId = objectName.split("_" + newDate)[0];
                        if (deviceImageNum.get(cameraId) == null) {
                            deviceImageNum.put(cameraId, 0);
                        }
                        deviceImageNum.put(cameraId, deviceImageNum.get(cameraId) + 1);
                        newInduceDeviceInfo.setCameraId(cameraId);

                        List<InduceDeviceInfo> induceDeviceInfos = this.induceDeviceMapper.selectDeviceInfoByCondition(newInduceDeviceInfo);
                        if (induceDeviceInfos.size() != 0) {
                            inducePestImgInfo.setDeviceId(induceDeviceInfos.get(0).getId());
                            inducePestImgInfo.setUserId(induceDeviceInfos.get(0).getUserId());

                        } else {
                            newInduceDeviceInfo.setName(cameraId);
                            induceDeviceMapper.insertDeviceInfo(newInduceDeviceInfo);
                            inducePestImgInfo.setDeviceId(newInduceDeviceInfo.getId());

                        }
                        inducePestImgInfo.setIsCaputreManual(0);

                        MultipartFile mFile = null;

                        try {
                            File file = new File(pathName);
                            FileInputStream fileInputStream = new FileInputStream(file);

                            String fileName = file.getName();
                            fileName = fileName.substring((fileName.lastIndexOf("/") + 1));
                            mFile = new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);



                            List<InduceDetectionLog> InduceDetectionLogs = inducePestModelDetection(mFile, inducePestImgInfo);
                            result.addAll(InduceDetectionLogs);
                            file.delete();
                        } catch (Exception e) {
                            log.error("封装文件出现错误：{}", e);
                            //e.printStackTrace();
                        }

                    }
                } catch (OSSException oe) {
                    System.out.println("Caught an OSSException, which means your request made it to OSS, "
                            + "but was rejected with an error response for some reason.");
                    System.out.println("Error Message:" + oe.getErrorMessage());
                    System.out.println("Error Code:" + oe.getErrorCode());
                    System.out.println("Request ID:" + oe.getRequestId());
                    System.out.println("Host ID:" + oe.getHostId());
                } catch (ClientException ce) {
                    System.out.println("Caught an ClientException, which means the client encountered "
                            + "a serious internal problem while trying to communicate with OSS, "
                            + "such as not being able to access the network.");
                    System.out.println("Error Message:" + ce.getMessage());
                } catch (ParseException e) {
                    e.printStackTrace();
                } finally {
                    if (ossClient != null) {
                        ossClient.shutdown();
                    }
                }
            }
        }

        for (String key : deviceImageNum.keySet()) {
            InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
            induceDeviceInfo.setCameraId(key);
            List<InduceDeviceInfo> induceDeviceInfos = this.induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);

            induceDeviceInfo.setId(induceDeviceInfos.get(0).getId());
            SelectInducePestImgInfo inducePestImgInfo = new SelectInducePestImgInfo();
            inducePestImgInfo.setDeviceId(induceDeviceInfo.getId());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date beginTime = calendar.getTime();
            calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            Date endTime = calendar.getTime();

            inducePestImgInfo.setBeginTime(beginTime);
            inducePestImgInfo.setEndTime(endTime);
            List<InducePestImgInfo> infoByCondition = inducePestImgMapper.getInfoByCondition(inducePestImgInfo);
            if(infoByCondition.size()>0){
                induceDeviceInfo.setStatus("在线");
            }else {
                induceDeviceInfo.setStatus("离线");
            }
            String onlineState = induceDeviceInfo.getStatus();
            Date date = new Date();
            // 创建SimpleDateFormat对象，指定字符串的日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 调用format() 方法，格式化时间，转换为指定格式字符串
            String now = sdf.format(date);
            Date updateTime = sdf.parse(now);
            String deviceName = induceDeviceInfo.getName();

            SerDevicePermi devicePermiInfo = devicePermiMapper.selectByDeviceSerial(induceDeviceInfo.getCameraId());
            devicePermiInfo.setOnlineState(onlineState);
            devicePermiInfo.setDeviceName(deviceName);
            devicePermiMapper.updateByPrimaryKeySelective(devicePermiInfo);
        }

        return result;
    }

    @Override
    public List<InduceDetectionLog> downImageFromOSSByTimeAndDeviceId(Integer deviceId, String beginDay, String endDay) {
        // 创建OSSClient实例。
        //List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();
        List<String> dates = MyDateUtil.calculateTimeInterval(beginDay, endDay);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, Integer> deviceImageNum = new HashMap<String, Integer>();
        List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();
        InduceDeviceInfo induceDeviceInfo = induceDeviceMapper.selectDeviceById(deviceId);


        deviceImageNum.put(induceDeviceInfo.getCameraId(), 0);


        Calendar calendar = Calendar.getInstance();


        for (String newDate : dates) {
            // 指定前缀，例如exampledir/object。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            String prefix = induceDeviceInfo.getCameraId() + "_";
            prefix = prefix + newDate;
            try {
                // 列举指定前缀的文件。
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
                listObjectsV2Request.setPrefix(prefix);
                ListObjectsV2Result listObjectsV2Result = ossClient.listObjectsV2(listObjectsV2Request);
                List<OSSObjectSummary> ossObjectSummaries = listObjectsV2Result.getObjectSummaries();

                for (OSSObjectSummary s : ossObjectSummaries) {
                    String objectName = s.getKey();
                    SelectInducePestImgInfo selectInducePestImgInfo = new SelectInducePestImgInfo();
                    calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    Date beginTime = calendar.getTime();
                    calendar.set(Calendar.HOUR_OF_DAY, 23);
                    calendar.set(Calendar.MINUTE, 59);
                    calendar.set(Calendar.SECOND, 59);
                    Date endTime = calendar.getTime();

                    selectInducePestImgInfo.setBeginTime(beginTime);
                    selectInducePestImgInfo.setEndTime(endTime);
                    boolean isHaveImage = false;  //判断数据库中是否有该图片了
                    for (InducePestImgInfo inducePestImgInfo : inducePestImgMapper.getInfoByCondition(selectInducePestImgInfo)) {
                        if (inducePestImgInfo.getImageName().equals(objectName)) {
                            isHaveImage = true;
                            break;
                        }
                    }
                    if (isHaveImage) {
                        continue;
                    }
                    String hoursMinuteSecond = objectName.split(newDate)[1].replace("_", "").split("\\.")[0];
                    String hours = hoursMinuteSecond.split("-")[0];
                    String minutes = hoursMinuteSecond.split("-")[1];
                    String seconds = hoursMinuteSecond.split("-")[2];
                    String imageTime = newDate + " " + hours + ":" + minutes + ":" + seconds;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date captureDate = sdf.parse(imageTime);
                    String pathName = RuoYiConfig.getDetectionPath() + File.separator + objectName;
                    ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
                    InducePestImgInfo inducePestImgInfo = new InducePestImgInfo();
                    //Long userIdL = SecurityUtils.getLoginUser().getUser().getUserId();
                    //Integer userId=Integer.valueOf(userIdL.intValue());
                    //inducePestImgInfo.setUserId(userId);
                    inducePestImgInfo.setCaptureTime(captureDate);
                    InduceDeviceInfo newInduceDeviceInfo = new InduceDeviceInfo();
                    String cameraId = objectName.split("_" + newDate)[0];
                    if (deviceImageNum.get(cameraId) == null) {
                        deviceImageNum.put(cameraId, 0);
                    }
                    deviceImageNum.put(cameraId, deviceImageNum.get(cameraId) + 1);
                    newInduceDeviceInfo.setCameraId(cameraId);

                    List<InduceDeviceInfo> induceDeviceInfos = this.induceDeviceMapper.selectDeviceInfoByCondition(newInduceDeviceInfo);
                    if (induceDeviceInfos.size() != 0) {
                        inducePestImgInfo.setDeviceId(induceDeviceInfos.get(0).getId());
                        inducePestImgInfo.setUserId(induceDeviceInfos.get(0).getUserId());

                    } else {
                        newInduceDeviceInfo.setName(cameraId);
                        induceDeviceMapper.insertDeviceInfo(newInduceDeviceInfo);
                        inducePestImgInfo.setDeviceId(newInduceDeviceInfo.getId());

                    }
                    inducePestImgInfo.setIsCaputreManual(0);

                    MultipartFile mFile = null;

                    try {
                        File file = new File(pathName);
                        FileInputStream fileInputStream = new FileInputStream(file);

                        String fileName = file.getName();
                        //System.out.println(pathName);
                        fileName = fileName.substring((fileName.lastIndexOf("/") + 1));
                        //System.out.println(fileName);
                        //System.out.println("-----------------------------------------------------------");
                        mFile = new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

                        List<InduceDetectionLog> InduceDetectionLogs = inducePestModelDetection(mFile, inducePestImgInfo);
                        result.addAll(InduceDetectionLogs);
                        file.delete();
                    } catch (Exception e) {
                        log.error("封装文件出现错误：{}", e);
                        //e.printStackTrace();
                    }

                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } catch (ParseException e) {
                e.printStackTrace();
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }


        for (String key : deviceImageNum.keySet()) {
            induceDeviceInfo = new InduceDeviceInfo();
            induceDeviceInfo.setCameraId(key);
            List<InduceDeviceInfo> induceDeviceInfos = this.induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);

            induceDeviceInfo.setId(induceDeviceInfos.get(0).getId());
            SelectInducePestImgInfo inducePestImgInfo = new SelectInducePestImgInfo();
            inducePestImgInfo.setDeviceId(induceDeviceInfo.getId());

            calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date beginTime = calendar.getTime();
            calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            Date endTime = calendar.getTime();

            inducePestImgInfo.setBeginTime(beginTime);
            inducePestImgInfo.setEndTime(endTime);
            List<InducePestImgInfo> infoByCondition = inducePestImgMapper.getInfoByCondition(inducePestImgInfo);
            if(infoByCondition.size()>0){
                induceDeviceInfo.setStatus("在线");
            }else {
                induceDeviceInfo.setStatus("离线");
            }
            this.induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);
        }

        return result;
    }

    @Override
    public List<InduceDetectionLog> autoCountAgain(Integer id) throws JsonProcessingException {
        InducePestImgInfo inducePestImgInfo = inducePestImgMapper.selectInfoById(id);
        List<InduceDetectionLog> InduceDetectionLogList = new ArrayList<>();
//        if(inducePestImgInfo.getTagManual()!=null ) {
            String images = inducePestImgInfo.getUrl();
            // upload() : 返回的就是文件路径
            //String images = FileUploadUtils.upload(RuoYiConfig.getDetectionPath(), file);
            String detectionImages = StringUtils.substringAfter(images, "profile");
            File imgFile = new File(profile + detectionImages);

            /* 解析识别结果构造实例存入数据库并返回, 检测不需要list集合，识别有多个可能，需要集合装载，其他的不需要 */

            ImgDrawCircleTool tool = new ImgDrawCircleTool();

        RpcRequest rpc = new RpcRequest("47.96.166.231", 10051, "siqing-files");
        try {
            log.info("发送图片进行检测");
            // 图片发送到Django进行识别
//            ResponseEntity<String> responseEntity = Threads.detectionRequest(profile + detectionImages, detectionUrl);
//            log.info("responseEntity------->" + responseEntity.getBody());
            // 图片通过rpc方式进行回调
            String upload_oss_name = StringUtils.substringAfter(images, "profile/");
//            String res = rpc.getRpcRes(upload_oss_name);
            String res = Threads.rpcRequest(upload_oss_name, rpc::getRpcRes);
            log.info("responseEntity=======>"+res);
            // json格式的数据转换成数组格式
//            InduceDetectionLogList = JSON.parseArray(responseEntity.getBody(), InduceDetectionLog.class);
//            log.info(InduceDetectionLogList.toString());
            InduceDetectionLogList = JSON.parseArray(res, InduceDetectionLog.class);
            log.info(InduceDetectionLogList.toString());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                rpc.shutdownChannel();
            }
            if (StringUtils.isNotNull(InduceDetectionLogList)) {
                for (InduceDetectionLog detection : InduceDetectionLogList) {
                    if (StringUtils.isNotNull(detection)) {

                        String tagNum = ParseString.getTagNum(detection.getTag());
                        log.info("检测结果：" + tagNum);
                        JSONObject jsonObject = JSON.parseObject(tagNum);
//                        int num_1 = 0, num_2 = 0, num_3 = 0, num_4 = 0, num_5 = 0;
//                        if (jsonObject.get("dm") != null) {
//                            num_1 = (int) jsonObject.get("dm");
//                        }
//                        if (jsonObject.get("ehm") != null) {
//                            num_2 = (int) jsonObject.get("ehm");
//                        }
//                        if (jsonObject.get("dzjym") != null) {
//                            num_3 = (int) jsonObject.get("dzjym");
//                        }
//                        if (jsonObject.get("cdtye") != null) {
//                            num_4 = (int) jsonObject.get("cdtye");
//                        }
//                        if (jsonObject.get("ymm") != null) {
//                            num_5 = (int) jsonObject.get("ymm");
//                        }
                        ObjectMapper objectMapper = new ObjectMapper();
                        Map<String, Integer> insectMap = objectMapper.readValue(tagNum, new TypeReference<Map<String, Integer>>() {});
                        int tagAllCount=getMapAllSum(insectMap);
                        if (inducePestImgInfo.getDeviceId() != null) {
                            InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
                            induceDeviceInfo.setId(inducePestImgInfo.getDeviceId());
                            List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);
                            if (induceDeviceInfos.size() > 0) {
                                induceDeviceInfo = induceDeviceInfos.get(0);

                                Integer maxInsectNumber = induceDeviceInfo.getMaxInsectNumber();
                                if (tagAllCount>maxInsectNumber) {
                                    induceDeviceInfo.setBoardStatus(0);
                                    induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);
                                } else {
                                    induceDeviceInfo.setBoardStatus(1);
                                    induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);
                                }
                            }

                        }
                        // 用来判断imgPest是否是模型能识别的，从而分别进行两种操作
                        boolean flagForPestIsModel=false;
                        Lure lure = new Lure();
                        lure.setCanModel(1);
                        List<Lure> lures = induceDeviceService.selectLure(lure);
                        // 提取lure字段生成新的List
                        List<String> induceModelPestList = lures.stream()
                                .map(Lure::getLure)
                                .collect(Collectors.toList());
                        Integer tagPestCount=0;
                        if(inducePestImgInfo.getImgPest()==null){
                            tagPestCount=0;
                        }else if(induceModelPestList.contains(inducePestImgInfo.getImgPest())){
                            flagForPestIsModel=true;
                            tagPestCount=insectMap.get(getPinYinHeadChar(inducePestImgInfo.getImgPest()));
                            if(tagPestCount==null){
                                tagPestCount=0;
                            }
                        }else {
                            tagPestCount=tagAllCount;
                        }
                        Integer tagOtherCount=(tagAllCount-tagPestCount<0)?0:tagAllCount-tagPestCount;

                        /*画框之后的结果图 resUrl  缩略图 已添加 */
                        List<String> tagList = JSON.parseArray(detection.getTag(), String.class);
                        //for (int i = 0; i < detection.getCorner().size(); i++) {
                        //    System.out.println(detection.getCorner().get(i).toString());
                        //}
                        String corner = "";
                        for (int i = 0; i < detection.getCorner().size(); i++) {
                            for (int j = 0; j < 4; j++) {
                                corner += Integer.toString(detection.getCorner().get(i)[j]);
                                corner += ",";
                            }
                        }
                        inducePestImgInfo.setTagForDraw(detection.getTag());
                        inducePestImgInfo.setCorner(corner);
//                        String resultPath = tool.doDrawRectangle(detection.getCorner(), tagList, profile + detectionImages, num_1, num_2, num_3, num_4,num_5,inducePestImgInfo.getImgPest()).replace(profile, Constants.RESOURCE_PREFIX);
                        String resultPath = tool.doDrawRectangle(detection.getCorner(), tagList, profile + detectionImages, tagPestCount,tagOtherCount,inducePestImgInfo.getImgPest(),flagForPestIsModel).replace(profile, Constants.RESOURCE_PREFIX);
                        log.info("res_path==>"+resultPath);
                        String tmp_read_path = profile + detectionImages;
                        log.info("read_path==>"+ tmp_read_path);

                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(inducePestImgInfo.getCaptureTime());
                        calendar.set(Calendar.HOUR_OF_DAY, 0);
                        calendar.set(Calendar.MINUTE, 0);
                        calendar.set(Calendar.SECOND, 0);
                        Date captureDay = calendar.getTime();

                        BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
                        beginTimeAndEndTimt.setBeginTime(captureDay);
                        beginTimeAndEndTimt.setDeviceId(inducePestImgInfo.getDeviceId());
                        List<String> LastCornerByDayAndDeviceId = inducePestImgMapper.selectLastCornerByDayAndDeviceId(beginTimeAndEndTimt);
//                        String cornerLastDay = inducePestImgMapper.selectLastCornerByDayAndDeviceId(beginTimeAndEndTimt).get(0);
                        String cornerLastDay ="";
                        if(LastCornerByDayAndDeviceId.size()!=0){
                            cornerLastDay=LastCornerByDayAndDeviceId.get(0);
                        }
                        boolean isNewBoard = isNewBoard(cornerLastDay, corner);
                        if (isNewBoard) {
                            inducePestImgInfo.setIsNewBoard(1);
                        } else {
                            inducePestImgInfo.setIsNewBoard(0);
                        }

                        inducePestImgInfo.setUpdateTime(new Date());
                        inducePestImgInfo.setResultUrl(resultPath);
                        inducePestImgInfo.setTag(ParseString.getTagNum(detection.getTag()));
                        inducePestImgInfo.setTagManual(inducePestImgInfo.getTag());
                        insertRecord(inducePestImgInfo);
                        inducePestImgMapper.updateReCountInfoById(inducePestImgInfo);
                        inducePestImgMapper.updateInfoById(inducePestImgInfo);
                    }
                }
                if (InduceDetectionLogList.size() == 0) {
                    System.out.println(inducePestImgInfo.getImageName()+"未检测到目标");
                    InduceDetectionLog InduceDetectionLog = new InduceDetectionLog();
                    InduceDetectionLog.setImagePath(inducePestImgInfo.getUrl());
                    InduceDetectionLog.setOriginalFileName(inducePestImgInfo.getImageName());
                    /*画框之后的结果图 resUrl  缩略图 已添加 */
                    InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
                    induceDeviceInfo.setId(inducePestImgInfo.getDeviceId());
                    induceDeviceInfo.setBoardStatus(1);
                    induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);

                    List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);
                    if(induceDeviceInfos.size()>0) {
                        induceDeviceInfo = induceDeviceInfos.get(0);

                        inducePestImgInfo.setDeviceName(induceDeviceInfo.getName());
                        inducePestImgInfo.setImgPest(judgePestFromLure(induceDeviceInfo.getLure()));
                    }
                    String resultPath = tool.doDrawRectangleAll0(profile + detectionImages,inducePestImgInfo.getImgPest()).replace(profile, Constants.RESOURCE_PREFIX);

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(inducePestImgInfo.getCaptureTime());
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    Date captureDay = calendar.getTime();

                    BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
                    beginTimeAndEndTimt.setBeginTime(captureDay);
                    beginTimeAndEndTimt.setDeviceId(inducePestImgInfo.getDeviceId());
                    List<String> LastCornerByDayAndDeviceId = inducePestImgMapper.selectLastCornerByDayAndDeviceId(beginTimeAndEndTimt);
                    String cornerLastDay = "";
                    if (LastCornerByDayAndDeviceId.size() != 0) {
                        cornerLastDay = LastCornerByDayAndDeviceId.get(0);
                    }

                    boolean isNewBoard = isNewBoard(cornerLastDay, "");
                    if (isNewBoard) {
                        inducePestImgInfo.setIsNewBoard(1);
                    } else {
                        inducePestImgInfo.setIsNewBoard(0);
                    }

                    inducePestImgInfo.setUpdateTime(new Date());
                    inducePestImgInfo.setTag(null).setResultUrl(resultPath).setCorner("").setTagManual(null);
//                    inducePestImgMapper.insertInducePestImgInfo(inducePestImgInfo);
                    inducePestImgMapper.updateReCountInfoById(inducePestImgInfo);
                    inducePestImgMapper.updateTagManual(inducePestImgInfo);
                    inducePestImgMapper.updateInfoById(inducePestImgInfo);
                    insertRecord(inducePestImgInfo);
                    log.info(inducePestImgInfo.toString());
                }

            }

//        }
        return InduceDetectionLogList;
    }

    public List<InduceDetectionLog> inducePestModelDetection(MultipartFile file, InducePestImgInfo inducePestImgInfo) throws IOException, ImageProcessingException, ParseException {
        String filename = file.getOriginalFilename(); //原始图片的名字
        // upload() : 返回的就是文件路径
        BufferedImage image = ImageIO.read(file.getInputStream());
        // 在图片上添加时间信息
        log.info("给原图绘制时间戳");
        // 定义正则表达式
        String regex = "\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(filename);

        if (matcher.find()) {
            // 提取匹配的时间信息
            String timeString = matcher.group();

            // 解析时间字符串
            LocalDateTime dateTime = LocalDateTime.parse(timeString, DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"));

            // 格式化为目标格式
            String formattedTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            image = ImageUtil.addTimestamp(formattedTime,image);
        }

        if(inducePestImgInfo.getDeviceId()!= null) {
            InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
            induceDeviceInfo.setId(inducePestImgInfo.getDeviceId());
            List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);
            if (induceDeviceInfos.size() > 0) {
                if(StringUtil.isNotEmpty(induceDeviceInfos.get(0).getManualId())) {
                    //在图片上添加设备信息
                    log.info("给原图绘制设备信息");
                    image = ImageUtil.addDeviceId(induceDeviceInfos.get(0).getManualId(), image);
                }
            }
        }
        // 将BufferedImage转换为自定义的MultipartFile
        MultipartFile multipartFileWithTimestamp = new BufferedImageMultipartFile(
                image,
                file.getName(),
                file.getOriginalFilename()
        );
        String images = FileUploadUtils.upload(RuoYiConfig.getDetectionPath(), multipartFileWithTimestamp);

        log.info("img upload success");
        String detectionImages = StringUtils.substringAfter(images, "profile");
        File imgFile = new File(profile + detectionImages);
        if(inducePestImgInfo.getCaptureTime()==null) {
            Date captureDate = ImageShootingTimeDate(imgFile);
            inducePestImgInfo.setCaptureTime(captureDate);
        }

        /* 解析识别结果构造实例存入数据库并返回, 检测不需要list集合，识别有多个可能，需要集合装载，其他的不需要 */
        List<InduceDetectionLog> InduceDetectionLogList = new ArrayList<>();
        ImgDrawCircleTool tool = new ImgDrawCircleTool();
        inducePestImgInfo.setImageName(file.getOriginalFilename()).setUrl(images).setThumUrl(images.replace("original", "thum"));

        RpcRequest rpc = new RpcRequest("47.96.166.231", 10051, "siqing-files");
        try {
            log.info("发送图片进行检测");
            // 图片发送到Django进行识别
//            ResponseEntity<String> responseEntity = Threads.detectionRequest(profile + detectionImages, detectionUrl);
//            log.info("responseEntity------->" + responseEntity.getBody());
            // 图片通过rpc方式进行回调
            String upload_oss_name = StringUtils.substringAfter(images, "profile/");
//            String res = rpc.getRpcRes(upload_oss_name);
            String res = Threads.rpcRequest(upload_oss_name, rpc::getRpcRes);
            log.info("responseEntity=======>"+res);
            // json格式的数据转换成数组格式
//            InduceDetectionLogList = JSON.parseArray(responseEntity.getBody(), InduceDetectionLog.class);
//            log.info(InduceDetectionLogList.toString());
            InduceDetectionLogList = JSON.parseArray(res, InduceDetectionLog.class);
            log.info(InduceDetectionLogList.toString());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            rpc.shutdownChannel();
        }

        for (InduceDetectionLog detection : InduceDetectionLogList) {
            if (StringUtils.isNotNull(detection)) {
                System.out.println(inducePestImgInfo.getImageName()+"检测到目标");

                String tagNum = ParseString.getTagNum(detection.getTag());
                log.info("检测结果：" + tagNum);
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Integer> insectMap = objectMapper.readValue(tagNum, new TypeReference<Map<String, Integer>>() {});
                int tagAllCount=getMapAllSum(insectMap);


                if(inducePestImgInfo.getDeviceId()!= null){
                    InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
                    induceDeviceInfo.setId(inducePestImgInfo.getDeviceId());
                    List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);
                    if(induceDeviceInfos.size()>0){
                        induceDeviceInfo = induceDeviceInfos.get(0);
                        induceDeviceInfo.setStatus("在线");
                        inducePestImgInfo.setImgPest(judgePestFromLure(induceDeviceInfo.getLure()));
                        Integer maxInsectNumber = induceDeviceInfo.getMaxInsectNumber();
                        if(tagAllCount>maxInsectNumber){
                            induceDeviceInfo.setBoardStatus(0);
                            induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);
                        }else {
                            induceDeviceInfo.setBoardStatus(1);
                            induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);
                        }
                    }

                }

                // 用来判断imgPest是否是模型能识别的，从而分别进行两种操作
                boolean flagForPestIsModel=false;
                Lure lure = new Lure();
                lure.setCanModel(1);
                List<Lure> lures = induceDeviceService.selectLure(lure);
                // 提取lure字段生成新的List
                List<String> induceModelPestList = lures.stream()
                        .map(Lure::getLure)
                        .collect(Collectors.toList());
                Integer tagPestCount=0;
                if(inducePestImgInfo.getImgPest()==null){
                    tagPestCount=0;
                }else if(induceModelPestList.contains(inducePestImgInfo.getImgPest())){
                    flagForPestIsModel=true;
                    tagPestCount=insectMap.get(getPinYinHeadChar(inducePestImgInfo.getImgPest()));
                    if(tagPestCount==null){
                        tagPestCount=0;
                    }
                }else {
                    tagPestCount=tagAllCount;
                }
                Integer tagOtherCount=(tagAllCount-tagPestCount<0)?0:tagAllCount-tagPestCount;

                /*画框之后的结果图 resUrl  缩略图 已添加 */
                List<String> tagList = JSON.parseArray(detection.getTag(), String.class);
                //for (int i = 0; i < detection.getCorner().size(); i++) {
                //    System.out.println(detection.getCorner().get(i).toString());
                //}
                String corner="";
                for (int i = 0; i < detection.getCorner().size(); i++) {
                    for (int j = 0; j < 4; j++) {
                        corner+=Integer.toString(detection.getCorner().get(i)[j]);
                        corner+=",";
                    }
                }
                inducePestImgInfo.setTagForDraw(detection.getTag());
                inducePestImgInfo.setCorner(corner);
                String resultPath = tool.doDrawRectangle(detection.getCorner(), tagList, profile + detectionImages, tagPestCount,tagOtherCount,inducePestImgInfo.getImgPest(),flagForPestIsModel).replace(profile, Constants.RESOURCE_PREFIX);
                log.info("res_path==>"+resultPath);
                String tmp_read_path = profile + detectionImages;
                log.info("read_path==>"+ tmp_read_path);

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(inducePestImgInfo.getCaptureTime());
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                Date captureDay = calendar.getTime();

                BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
                beginTimeAndEndTimt.setBeginTime(captureDay);
                beginTimeAndEndTimt.setDeviceId(inducePestImgInfo.getDeviceId());
                List<String> LastCornerByDayAndDeviceId = inducePestImgMapper.selectLastCornerByDayAndDeviceId(beginTimeAndEndTimt);
                String cornerLastDay ="";
                if(LastCornerByDayAndDeviceId.size()!=0){
                    cornerLastDay=LastCornerByDayAndDeviceId.get(0);
                }

                boolean isNewBoard = isNewBoard(cornerLastDay, corner);
                if(isNewBoard){
                    inducePestImgInfo.setIsNewBoard(1);
                }else {
                    inducePestImgInfo.setIsNewBoard(0);
                }

                inducePestImgInfo.setUpdateTime(new Date());
                inducePestImgInfo.setTag(ParseString.getTagNum(detection.getTag())).setResultUrl(resultPath);
                inducePestImgInfo.setTagManual(inducePestImgInfo.getTag());
                inducePestImgInfo.setTagForDraw(detection.getTag());

                SelectInducePestImgInfo selectInducePestImgInfo = new SelectInducePestImgInfo();
                selectInducePestImgInfo.setImageName(inducePestImgInfo.getImageName());
                List<InducePestImgInfo> infoByCondition = inducePestImgMapper.getInfoByCondition(selectInducePestImgInfo);
                if(infoByCondition.size()>0){
                    System.out.println(inducePestImgInfo.getImageName()+"重命名后的图片已被上传，不再重复上传");
                }else if(StringUtils.isEmpty(selectInducePestImgInfo.getImageName())){
                    System.out.println("ImageName为空或null，有异常，禁止上传");
                }else {
                    inducePestImgMapper.insertInducePestImgInfo(inducePestImgInfo);
                }

            }
        }
        if(InduceDetectionLogList.size()==0){
            System.out.println(inducePestImgInfo.getImageName()+"未检测到目标");
            InduceDetectionLog InduceDetectionLog = new InduceDetectionLog();
            InduceDetectionLog.setImagePath(inducePestImgInfo.getUrl());
            InduceDetectionLog.setOriginalFileName(inducePestImgInfo.getImageName());

            /*画框之后的结果图 resUrl  缩略图 已添加 */
            InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
            induceDeviceInfo.setId(inducePestImgInfo.getDeviceId());
            induceDeviceInfo.setBoardStatus(1);
            induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);

            List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);
            if(induceDeviceInfos.size()>0) {
                induceDeviceInfo = induceDeviceInfos.get(0);

                inducePestImgInfo.setDeviceName(induceDeviceInfo.getName());
                inducePestImgInfo.setImgPest(judgePestFromLure(induceDeviceInfo.getLure()));
            }
            String resultPath = tool.doDrawRectangleAll0(profile + detectionImages,inducePestImgInfo.getImgPest()).replace(profile, Constants.RESOURCE_PREFIX);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(inducePestImgInfo.getCaptureTime());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date captureDay = calendar.getTime();

            BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
            beginTimeAndEndTimt.setBeginTime(captureDay);
            beginTimeAndEndTimt.setDeviceId(inducePestImgInfo.getDeviceId());
            List<String> LastCornerByDayAndDeviceId = inducePestImgMapper.selectLastCornerByDayAndDeviceId(beginTimeAndEndTimt);
            String cornerLastDay ="";
            if(LastCornerByDayAndDeviceId.size()!=0){
                cornerLastDay=LastCornerByDayAndDeviceId.get(0);
            }

            boolean isNewBoard = isNewBoard(cornerLastDay, "");
            if(isNewBoard){
                inducePestImgInfo.setIsNewBoard(1);
            }else {
                inducePestImgInfo.setIsNewBoard(0);
            }



            inducePestImgInfo.setUpdateTime(new Date());
            inducePestImgInfo.setTag(null).setResultUrl(resultPath).setCorner("");
            inducePestImgInfo.setTagManual(inducePestImgInfo.getTag());
            SelectInducePestImgInfo selectInducePestImgInfo = new SelectInducePestImgInfo();
            selectInducePestImgInfo.setImageName(inducePestImgInfo.getImageName());
            List<InducePestImgInfo> infoByCondition = inducePestImgMapper.getInfoByCondition(selectInducePestImgInfo);
            if(infoByCondition.size()>0){
                System.out.println(inducePestImgInfo.getImageName()+"重命名后的图片已被上传，不再重复上传");
            }else if(StringUtils.isEmpty(selectInducePestImgInfo.getImageName())){
                System.out.println("ImageName为空或null，有异常，禁止上传");
            }else {
                inducePestImgMapper.insertInducePestImgInfo(inducePestImgInfo);
            }
            log.info(inducePestImgInfo.toString());
            InduceDetectionLogList.add(InduceDetectionLog);
        }

        return InduceDetectionLogList;

    }

    @Override
    public Integer updateBoard(Integer id,Integer isNewBoard) {
        InducePestImgInfo inducePestImgInfo = new InducePestImgInfo();
        inducePestImgInfo.setId(id).setIsNewBoard(isNewBoard);
        insertRecord(inducePestImgInfo);
        return inducePestImgMapper.updateBoard(inducePestImgInfo);
    }

    @Override
    public Integer updateTagManual(Integer id, Integer dm, Integer ehm, Integer dzjym, Integer cdtye,Integer ymm) {
        InducePestImgInfo inducePestImgInfo=new InducePestImgInfo();
        String tagManual = numberToJsonTag(dm, ehm, dzjym, cdtye,ymm);
        inducePestImgInfo.setId(id).setTagManual(tagManual);
        insertRecord(inducePestImgInfo);
        return inducePestImgMapper.updateTagManual(inducePestImgInfo);
    }

    @Override
    public Integer deleteImgInfo(int id) {
        return inducePestImgMapper.deleteImgInfo(id);
    }



    /**
     * 根据时间从OSS拉取图片

     * @param beginTime
     * @param endTime
     * @return
     */
    public  List<InduceDetectionLog> getImageFromOSSByTime(Date beginTime, Date endTime,Integer isCaptureManual) {
        List<InduceDetectionLog> result=new ArrayList<InduceDetectionLog>();
        // 创建OSSClient实例。

        List<InduceDeviceInfo> induceDeviceInfosForCamera = induceDeviceMapper.selectAllDeviceInfo();
        Map<String, Integer> deviceImageNum = new HashMap<String, Integer>();
        for (InduceDeviceInfo induceDeviceInfo : induceDeviceInfosForCamera) {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);




            deviceImageNum.put(induceDeviceInfo.getCameraId(), 0);
            // 指定前缀，例如exampledir/object。
            String prefix = induceDeviceInfo.getCameraId()+"_";
            Calendar calendar = Calendar.getInstance();

            calendar.setTime(new Date());					//放入Date类型数据

            int year = calendar.get(Calendar.YEAR);//获取年份
            int month = calendar.get(Calendar.MONTH)+1;//获取月份
            int date = calendar.get(Calendar.DATE);//获取日

            String monthSt="";
            if(month<10){
                monthSt="0"+month;
            }else {
                monthSt=month+"";
            }
            String dateSt="";
            if(date<10){
                dateSt="0"+date;
            }else {
                dateSt=date+"";
            }
            String pathDay= year +"-"+ monthSt +"-"+ dateSt;
            prefix=prefix+pathDay;
            try {
                // 列举指定前缀的文件。
                ListObjectsV2Request listObjectsV2Request = new ListObjectsV2Request(bucketName);
                listObjectsV2Request.setPrefix(prefix);
                ListObjectsV2Result listObjectsV2Result = ossClient.listObjectsV2(listObjectsV2Request);
                List<OSSObjectSummary> ossObjectSummaries = listObjectsV2Result.getObjectSummaries();

                for (OSSObjectSummary s : ossObjectSummaries) {
                    String objectName = s.getKey();

                    String hoursMinuteSecond=objectName.split(pathDay)[1].replace("_","").split("\\.")[0];
                    String hours=hoursMinuteSecond.split("-")[0];
                    String minutes=hoursMinuteSecond.split("-")[1];
                    String seconds=hoursMinuteSecond.split("-")[2];
                    String imageTime=pathDay+" "+hours+":"+minutes+":"+seconds;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date captureDate = sdf.parse(imageTime);
                    if(belongCalendar(captureDate,beginTime,endTime)){

                        String pathName = RuoYiConfig.getDetectionPath()+File.separator+objectName;
                        System.out.println(pathName);
                        ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
                        InducePestImgInfo inducePestImgInfo = new InducePestImgInfo();

                        inducePestImgInfo.setCaptureTime(captureDate);
                        InduceDeviceInfo newInduceDeviceInfo = new InduceDeviceInfo();
                        String captureId=objectName.split("_"+pathDay)[0];

                        newInduceDeviceInfo.setCameraId(captureId);

                        List<InduceDeviceInfo> induceDeviceInfos = this.induceDeviceMapper.selectDeviceInfoByCondition(newInduceDeviceInfo);
                        if(induceDeviceInfos.size()!=0){
                            inducePestImgInfo.setDeviceId(induceDeviceInfos.get(0).getId());
                            inducePestImgInfo.setUserId(induceDeviceInfos.get(0).getUserId());

                        }else {
                            newInduceDeviceInfo.setName(captureId);
                            induceDeviceMapper.insertDeviceInfo(newInduceDeviceInfo);
                            inducePestImgInfo.setDeviceId(newInduceDeviceInfo.getId());

                        }


                        inducePestImgInfo.setIsCaputreManual(isCaptureManual);

                        MultipartFile mFile = null;

                        try {
                            File file = new File(pathName);
                            FileInputStream fileInputStream = new FileInputStream(file);

                            String fileName = file.getName();
                            fileName = fileName.substring((fileName.lastIndexOf("/") + 1));
                            mFile =  new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

                            List<InduceDetectionLog> InduceDetectionLogs = inducePestModelDetection(mFile, inducePestImgInfo);
                            result.addAll(InduceDetectionLogs);
                            file.delete();
                        } catch (Exception e) {
                            log.error("封装文件出现错误：{}", e);
                            //e.printStackTrace();
                        }
                    }
                }
            }catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } catch (ParseException e) {
                e.printStackTrace();
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }


        for (String key : deviceImageNum.keySet()) {
            InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
            induceDeviceInfo.setCameraId(key);
            List<InduceDeviceInfo> induceDeviceInfos = this.induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);

            induceDeviceInfo.setId(induceDeviceInfos.get(0).getId());
            SelectInducePestImgInfo inducePestImgInfo = new SelectInducePestImgInfo();
            inducePestImgInfo.setDeviceId(induceDeviceInfo.getId());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            beginTime = calendar.getTime();
            calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            endTime = calendar.getTime();

            inducePestImgInfo.setBeginTime(beginTime);
            inducePestImgInfo.setEndTime(endTime);
            List<InducePestImgInfo> infoByCondition = inducePestImgMapper.getInfoByCondition(inducePestImgInfo);
            if(infoByCondition.size()>0){
                induceDeviceInfo.setStatus("在线");
            }else {
                induceDeviceInfo.setStatus("离线");
            }
            this.induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);
        }

        return result;
    }

    @Override
    public InducePestImgInfo drawByManual(Integer id, String width, String height, String type, String position, Integer addOrCut) throws IOException {



        InducePestImgInfo inducePestImgInfo = inducePestImgMapper.selectInfoById(id);
        String detectionImages = StringUtils.substringAfter(inducePestImgInfo.getUrl(), "profile");
        File imgFile = new File(profile + detectionImages);
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imgFile));
        Integer originHeight = bufferedImage.getHeight();
        Integer originWidth = bufferedImage.getWidth();
        Integer drawWidth=null;
        if(width!=null && width.length()!=0){
            drawWidth=Integer.parseInt(width);
        }
        Integer drawHeight=null;
        if(height!=null && height.length()!=0){
            drawHeight=Integer.parseInt(height);
        }

        String[] positionsString = position.split(",");


        int size = positionsString.length;
        int [] positionsInt = new int [size];
        for(int i=0; i<size; i++) {
            positionsInt[i] = Integer.parseInt(positionsString[i]);
        }
        String positionString="";
        for (int i = 0; i < positionsInt.length / 4; i++) {
            positionsInt[4 * i + 2] = positionsInt[4 * i] + positionsInt[4 * i + 2];  //左上坐标 x，y,分别加上画框的宽高，得到右下角坐标
            positionsInt[4 * i + 3] = positionsInt[4 * i + 1] + positionsInt[4 * i + 3];
            float scaleWidth = 1;//缩放比例
            float scaleHeight = 1;//缩放比例
            if (originHeight != null && drawHeight != null && drawHeight != 0) {
                scaleHeight = (float) originHeight / (float) drawHeight;
            }
            if (originWidth != null && drawWidth != null && drawWidth != 0) {
                scaleWidth = (float) originWidth / (float) drawWidth;
            }
            if(drawWidth == null || drawWidth == 0){
                scaleWidth=scaleHeight;
            }
            if(drawHeight == null || drawHeight == 0){
                scaleHeight=scaleWidth;
            }
            log.info("scaleHeight =" + scaleHeight);
            log.info("scaleWidth =" + scaleWidth);

            positionsInt[4 * i] = (int) (positionsInt[4 * i] * scaleWidth);
            positionsInt[4 * i + 1] = (int) (positionsInt[4 * i + 1] * scaleHeight);
            positionsInt[4 * i + 2] = (int) (positionsInt[4 * i + 2] * scaleWidth);
            positionsInt[4 * i + 3] = (int) (positionsInt[4 * i + 3] * scaleHeight);
            //positionString = positionString + ",[" + positionsInt[4 * i] + "," + positionsInt[4 * i + 1] + "," + positionsInt[4 * i + 2] + "," + positionsInt[4 * i + 3] + "]";
            positionString = positionString  + positionsInt[4 * i] + "," + positionsInt[4 * i + 1] + "," + positionsInt[4 * i + 2] + "," + positionsInt[4 * i + 3]+",";
        }
        if (addOrCut == 1) {
            String tagForDraw="";
            if(inducePestImgInfo.getTagForDraw()!=null && inducePestImgInfo.getTagForDraw().length()!=0){
                tagForDraw = inducePestImgInfo.getTagForDraw();
                tagForDraw=tagForDraw.split("]")[0];
            }else {
                tagForDraw="[";
            }


            for(int i=0;i<positionsString.length/4;i++){
                tagForDraw=tagForDraw+",\""+type+"\"";
            }
            tagForDraw=tagForDraw+"]";
            tagForDraw = tagForDraw.replace("[,", "[");
            inducePestImgInfo.setTagForDraw(tagForDraw);

            String corner=inducePestImgInfo.getCorner()+positionString;
            inducePestImgInfo.setCorner(corner);
            inducePestImgInfo.setTagManual(ParseString.getTagNum(tagForDraw));
            ArrayList<int[]> cornerList = new ArrayList<>();
            String[] corners = corner.split(",");
            size = corners.length;
            int [] cornerInt = new int [size];
            for(int i=0; i<size; i++) {
                cornerInt[i] = Integer.parseInt(corners[i]);
            }
            for (int i =0 ;i<cornerInt.length/4;i=i+1){

                int[] cornerArray=Arrays.copyOfRange(cornerInt,i*4,i*4+4);
                cornerList.add(cornerArray);
            }
            String tagNum = ParseString.getTagNum(tagForDraw);
            log.info("检测结果：" + tagNum);
            JSONObject jsonObject = JSON.parseObject(tagNum);
            int num_1 = 0, num_2 = 0, num_3 = 0, num_4 = 0,num_5 = 0;
            if (jsonObject.get("dm") != null) {
                num_1 = (int) jsonObject.get("dm");
            }
            if (jsonObject.get("ehm") != null) {
                num_2 = (int) jsonObject.get("ehm");
            }
            if (jsonObject.get("dzjym") != null) {
                num_3 = (int) jsonObject.get("dzjym");
            }
            if (jsonObject.get("cdtye") != null) {
                num_4 = (int) jsonObject.get("cdtye");
            }
            if (jsonObject.get("ymm") !=null){
                num_5 = (int) jsonObject.get("ymm");
            }

            String tagManual = numberToJsonTag(num_1, num_2, num_3, num_4, num_5);
            inducePestImgInfo.setTagManual(tagManual);
            ImgDrawCircleTool tool = new ImgDrawCircleTool();
            List<String> tagList = JSON.parseArray(tagForDraw, String.class);
            tool.doDrawRectangle(cornerList, tagList, profile + detectionImages, num_1, num_2, num_3, num_4,num_5,inducePestImgInfo.getImgPest()).replace(profile, Constants.RESOURCE_PREFIX);
            insertRecord(inducePestImgInfo);
        }else if (addOrCut==0){
            //删去画框
            String tagForCut; //   tagForCut：删除画框后的tag
            tagForCut = inducePestImgInfo.getTagForDraw();
            if(tagForCut==null){
                tagForCut="";
            }
            tagForCut = tagForCut.replace("[","").replace("]","");
            String[] tagForCutString= tagForCut.split(",");
            log.info("原画框手动修改的tag" + Arrays.toString(tagForCutString));
            String oriCorner = inducePestImgInfo.getCorner();//原始框信息
            String[] oriCorners = oriCorner.replaceAll("\\[","").replaceAll("]","").split(",");
            log.info(oriCorner.replaceAll("\\[","").replaceAll("]",""));
            Integer length = oriCorners.length;
            int[] oriCornerInt = new int[length];
            for(int i = 0; i < length; i++){
                oriCornerInt[i] = Integer.parseInt(oriCorners[i]);
            }
            List<String> tagForCutList = Arrays.asList(tagForCutString);
            List<String> arrList = new ArrayList<>(tagForCutList);//为了避免出现UnsupportedOperationException错误
            List<String> tagForCutListNew = new ArrayList<>();
            log.info("删减前的tagList" + arrList);
            List<Integer> record = new ArrayList<>();//记录下标
            List<Integer> recordList = new ArrayList<>(record);
            //在cornerInt数组里寻找被positionInt包含的数
            for(int i = 0; i < length / 4; i++){ // i:0 1 2
                int[] cornerArray = Arrays.copyOfRange(oriCornerInt, i * 4, i * 4 + 4);
                for(int j = 0 ;j < positionsInt.length / 4; j++){ // j:0 1
                    int[] positionArray = Arrays.copyOfRange(positionsInt,j * 4,j * 4 + 4);
                    if(IsContain(positionArray,cornerArray) && arrList.get(i).equals("\""+type+"\"")){
                        recordList.add(i);
                        log.info("记录的下标为:" + recordList);
                    }
                }
            }

            int sizeNew = recordList.size();
            for(int i = 0;i < arrList.size();i++){
                if(recordList.contains(i)){
                    continue;
                }
                tagForCutListNew.add(arrList.get(i));
            }
            log.info("tagForCutListNew: " + tagForCutListNew);
            int [] positionIntNew = new int[sizeNew * 4];//对应属于图上的框
            log.info("oriCornerInt = " + Arrays.toString(oriCornerInt));
            log.info("recordList = " + recordList);
            positionIntNew = getTheElement(oriCornerInt,recordList);

            log.info("positionIntNew:" + Arrays.toString(positionIntNew));

            String positionStringNew="";
            for(int i =0; i < sizeNew; i++){
                positionStringNew = positionStringNew + "," +positionIntNew[4 * i] + "," + positionIntNew[4 * i + 1] + "," + positionIntNew[4 * i + 2] + "," + positionIntNew[4 * i + 3] ;
            }
            positionStringNew = positionStringNew.replaceFirst(",", "");
            log.info("positionStringNew:" + positionStringNew);
            //log.info("删减后的tagList" + tagForCutListNew);
            String tagForCutByJoin = StringUtils.join(tagForCutListNew,",");
            if(tagForCutByJoin !="") {
                tagForCut = "[" + tagForCutByJoin + "]";
            }else {
                tagForCut = tagForCutByJoin;
            }
            log.info("删减后的tag:" + tagForCut);
            inducePestImgInfo.setTagForDraw(tagForCut);
//            1962,1091,2045,1179,2080,955,2270,1018,1074,729,1260,852,1403,733,1597,856,
            String corner = inducePestImgInfo.getCorner().replace( positionStringNew,"");
//            corner = StringUtils.removeEnd(corner,"]");
//            corner = corner.replaceFirst("\\[","");
//            if(corner.endsWith(",")){
//                corner = StringUtils.removeEnd(corner,",");
//            }
//            if(corner.startsWith(",")){
//                corner = corner.replaceFirst(",","");
//            }
//            if(corner != "" && !corner.isEmpty()) {
//                corner = "[" + corner + "]";
//            }
            if (corner!=null && corner.endsWith(",")) {
                corner = corner.substring(0, corner.length() - 1);
            }
            corner = corner.replaceAll(",+", ",");
            log.info("corner: " + corner);

            inducePestImgInfo.setCorner(corner);
            corner = corner.replaceAll("\\[","").replaceAll("]","");
            ArrayList<int[]> cornerList = new ArrayList<>();
            if(!corner.isEmpty()){

                String[] corners = corner.split(",");
                log.info(Arrays.toString(corners));
                size = corners.length;
                log.info("size:" + size);
                int[] cornerInt = new int[size];
                for (int i = 0; i < size; i++) {
                    cornerInt[i] = Integer.parseInt(corners[i]);
                }
                for (int i = 0; i < cornerInt.length / 4; i++) {

                    int[] cornerArray = Arrays.copyOfRange(cornerInt, i * 4, i * 4 + 4);
                    cornerList.add(cornerArray);
                }
            }
            String tagNum = ParseString.getTagNum(tagForCut);
            log.info("检测结果：" + tagNum);
            JSONObject jsonObject = JSON.parseObject(tagNum);
            int num_1 = 0, num_2 = 0, num_3 = 0, num_4 = 0,num_5 = 0;
            if (jsonObject.get("dm") != null) {
                num_1 = (int) jsonObject.get("dm");
            }
            if (jsonObject.get("ehm") != null) {
                num_2 = (int) jsonObject.get("ehm");
            }
            if (jsonObject.get("dzjym") != null) {
                num_3 = (int) jsonObject.get("dzjym");
            }
            if (jsonObject.get("cdtye") != null) {
                num_4 = (int) jsonObject.get("cdtye");
            }
            if (jsonObject.get("ymm") !=null){
                num_5 = (int) jsonObject.get("ymm");
            }
            String tagManual = numberToJsonTag(num_1, num_2, num_3, num_4,num_5);
            inducePestImgInfo.setTagManual(tagManual);
            ImgDrawCircleTool tool = new ImgDrawCircleTool();
            List<String> tagList = JSON.parseArray(tagForCut, String.class);

            tool.doDrawRectangle(cornerList, tagList, profile + detectionImages, num_1+num_2+num_3+num_4+num_5,inducePestImgInfo.getImgPest()).replace(profile, Constants.RESOURCE_PREFIX);
            insertRecord(inducePestImgInfo);
        }

        inducePestImgMapper.updateInfoById(inducePestImgInfo);
        InducePestImgInfo result = inducePestImgMapper.selectInfoById(id);
        InducePestNumType inducePestNumTypeForCount=null;
        if(result.getTagManual()==null){
            inducePestNumTypeForCount = json2InsectTypeString(result.getTag());
        }else {
            inducePestNumTypeForCount = json2InsectTypeString(result.getTagManual());
        }
        result.setTagCount(inducePestNumTypeForCount.getSumCount());

        return result;
    }

    public Integer getMapAllSum(Map<String, Integer> insectMap){
        if(insectMap==null){
            return 0;
        }
        int totalQuantity = 0;
        for (int quantity : insectMap.values()) {
            if(quantity<0){
                continue;
            }
            totalQuantity += quantity;
        }
        return totalQuantity;
    }

    /**
     * 得到中文首字母
     *
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str) {

        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        convert = convert.replaceAll("[^A-Z^a-z^0-9]", "");
        return convert;
    }


    /**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {

        if (nowTime.getTime() == beginTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 记录修改值
     * @param newInducePestImgInfo
     * @return
     */
    public void insertRecord(InducePestImgInfo newInducePestImgInfo) {
        ChangeRecord changeRecord = new ChangeRecord();
        changeRecord.setChangeTable("ser_induce_device_info");
        changeRecord.setUpdateTime(new Date());
        changeRecord.setChangeInfoId(newInducePestImgInfo.getId());
        InducePestImgInfo oldInducePestImgInfo = inducePestImgMapper.selectInfoById(newInducePestImgInfo.getId());
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        changeRecord.setUserId(Integer.valueOf(userId.intValue()));
        try {
            //通过getDeclaredFields()⽅法获取对象类中的所有属性（含私有）
            Field[] newFields = newInducePestImgInfo.getClass().getDeclaredFields();
            for (Field newField : newFields) {
                //设置允许通过反射访问私有变量
                newField.setAccessible(true);
                //获取字段属性名称
                String name = newField.getName();
                if(name.equals("id")){
                    continue;
                }
                if (newField.get(newInducePestImgInfo) != null&& newField.get(newInducePestImgInfo).toString().length()!=0) {
                    changeRecord.setChangeKey(name);
                    //获取字段的值

                    String value = newField.get(newInducePestImgInfo).toString();
                    changeRecord.setChangeNewValue(value);
                    Field[] oldFields = oldInducePestImgInfo.getClass().getDeclaredFields();
                    for (Field oldField : oldFields) {
                        oldField.setAccessible(true);
                        if (oldField.getName().equals(name)) {
                            if(oldField.get(oldInducePestImgInfo)==null){
                                changeRecord.setChangeOldValue(null);
                            }else {
                                changeRecord.setChangeOldValue(oldField.get(oldInducePestImgInfo).toString());
                            }
                            break;
                        }
                    }
                    if(changeRecord.getChangeNewValue().equals(changeRecord.getChangeOldValue())){
                        continue;
                    }
                    changeRecordMapper.insertChangeInfo(changeRecord);
                }
                //其他⾃定义操作
            }
        } catch (Exception ex) {
            //处理异常
        }
    }


    /**
     * 添加 thumbnail 标签
     */
    private static String addThum(String srcPath){
        String res = "";
        if (StringUtils.isNotNull(srcPath)){
            String[] str = new String[2];
            /* \\. 转义字符，相当于 . ,分隔出.前后的内容 */
            str = srcPath.split("\\.");
            res = str[0] + "__thum." + str[1];
        }
        return res;
    }

    /**
     * 从oriCornerInt(框信息)中取出指定元素  1个下标取连续4个元素
     * @param oriCornerInt
     * @param index
     * @return
     */
    private int[] getTheElement(int[] oriCornerInt, List<Integer> index) {
        int[] cornerInt = new int[index.size() * 4];
        for(int i = 0;i < index.size();i++) {
            cornerInt[4 * i] = oriCornerInt[index.get(i) * 4];
            cornerInt[4 * i + 1] = oriCornerInt[index.get(i) * 4 + 1];
            cornerInt[4 * i + 2] = oriCornerInt[index.get(i) * 4 + 2];
            cornerInt[4 * i + 3] = oriCornerInt[index.get(i) * 4 + 3];
        }
        return cornerInt;
    }

    /**
     * 删除画框时调用
     * 比较前端传来的画框信息是否在原画框信息中
     * @param positionArray  前端传来的画框信息转化的数组
     * @param cornerArray  原画框信息转化的数组
     * @return
     */
    private boolean IsContain(int[]positionArray,int[]cornerArray) {
        if (positionArray.length != 0 && cornerArray.length != 0) {
            int length = positionArray.length;  //4
            if (positionArray[0] <= cornerArray[0] && positionArray[1] <= cornerArray[1] && positionArray[2] >= cornerArray[2] && positionArray[3] >= cornerArray[3]) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }
    }



    /**
     *
     * @param file
     * @return 返回Date类型
     * @throws ImageProcessingException
     * @throws IOException
     */
    public static Date ImageShootingTimeDate(File file) throws ImageProcessingException, IOException, ParseException, ParseException {
        Date date;
        String[] array = new String[3];
        //如果你对图片的格式有限制，可以直接使用对应格式的Reader如：JPEGImageReader
        ImageMetadataReader.readMetadata(file)
                .getDirectories().forEach(v ->
                        v.getTags().forEach(t -> {
                            System.out.println(t.getTagName() + " ： " + t.getDescription());
                            switch (t.getTagName()) {
                                case "Date/Time Original":
                                    array[1] = t.getDescription();
                                    break;
                                case "File Modified Date":
                                    System.out.println(t);
                                    array[2] = t.getDescription();
                                default:
                                    break;
                            }
                        })
                );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        if(array[1]!=null) {
            date = sdf.parse(array[1]);
            return date;
        }
        String[] times=array[2].split(" ");
        String result=times[5]+":";
        switch (times[1]){
            case "一月":
                result+="01:";
                break;
            case "二月":
                result+="02:";
                break;
            case "三月":
                result+="03:";
                break;
            case "四月":
                result+="04:";
                break;
            case "五月":
                result+="05:";
                break;
            case "六月":
                result+="06:";
                break;
            case "七月":
                result+="07:";
                break;
            case "八月":
                result+="08:";
                break;
            case "九月":
                result+="09:";
                break;
            case "十月":
                result+="10:";
                break;
            case "十一月":
                result+="11:";
                break;
            case "十二月":
                result+="12:";
                break;
        }
        result+=times[2]+" "+times[3];

        if(array[2]!=null) {
            date = sdf.parse(result);
        }else{
            date=new Date();
        }
        //System.out.println(date);
        return date;
    }

    /**
     * 计算图片IOU
     *
     * @param
     * @return 等级
     */
    public static boolean isNewBoard(String cornerYes,String corner) {
        if(cornerYes==null){
            cornerYes="";
        }
        if(corner==null){
            corner="";
        }
        if(cornerYes.length()==0 && corner.length()==0) {
            return false;
        }else if(cornerYes.length()==0 && corner.length()!=0){
            return false;
        }else if(cornerYes.equals(corner)) {
            return false;
        }else if (cornerYes.length()!=0 && corner.length()==0){
            return true;
        }else {
            String[] cornerYesArray=cornerYes.split(",");
            String[] cornerArray=corner.split(",");
            int sameBox=0;
            for (int i = 0; i < cornerYesArray.length; i=i+4) {
                Rect rectYes = new Rect();
                rectYes.setX(Integer.parseInt(cornerYesArray[i]));
                rectYes.setY(Integer.parseInt(cornerYesArray[i+1]));
                rectYes.setWidth(Integer.parseInt(cornerYesArray[i+2])-Integer.parseInt(cornerYesArray[i]));
                rectYes.setHeight(Integer.parseInt(cornerYesArray[i+3])-Integer.parseInt(cornerYesArray[i+1]));
                for (int j = 0; j < cornerArray.length; j=j+4) {
                    Rect rect = new Rect();
                    rect.setX(Integer.parseInt(cornerArray[j]));
                    rect.setY(Integer.parseInt(cornerArray[j+1]));
                    rect.setWidth(Integer.parseInt(cornerArray[j+2])-Integer.parseInt(cornerArray[j]));
                    rect.setHeight(Integer.parseInt(cornerArray[j+3])-Integer.parseInt(cornerArray[j+1]));
                    float result = iouCompute(rectYes, rect);
                    if(result>=0.7){
                        sameBox++;
                        if(sameBox>=Math.floor(cornerYesArray.length/4/2)){
                            return false;
                        }
                        break;
                    }
                }
            }
            return true;
        }
    }

    /**
     * 计算图片IOU
     *
     * @param
     * @return 等级
     */
    public static float iouCompute(Rect rect1, Rect rect2) {
        int leftColumnMax = Math.max(rect1.getX(), rect2.getX());
        int rightColumnMin = Math.min(rect1.getX()+rect1.getWidth(),rect2.getX()+rect2.getWidth());
        int upRowMax = Math.max(rect1.getY(), rect2.getY());
        int downRowMin = Math.min(rect1.getY()+rect1.getHeight(),rect2.getY()+ rect2.getHeight());

        if (leftColumnMax>=rightColumnMin || downRowMin<=upRowMax){
            return 0;
        }

        int s1 = rect1.getWidth()*rect1.getHeight();
        int s2 = rect2.getWidth()*rect2.getHeight();
        float sCross = (downRowMin-upRowMax)*(rightColumnMin-leftColumnMax);
        return sCross/(s1+s2-sCross);
    }

    /**
     * 通过诱芯名获得害虫名
     *
     * @param
     * @return 等级
     */
    public static String judgePestFromLure(String lure) {
        String result="";
        if(lure==null){
            result="";
            return result;
        }
        if(lure.contains("草地贪夜蛾")){
            result="草地贪夜蛾";
        }else if(lure.contains("稻纵卷叶螟")){
            result="稻纵卷叶螟";
        }else if(lure.contains("二化螟")){
            result="二化螟";
        }else{
            result=lure.split("诱芯")[0];
        }
        return result;
    }

    /**
     * 将虫子数量转成tag标签
     *
     * @param
     * @return 等级
     */
    public static String numberToJsonTag(Integer dm,Integer ehm,Integer dzjym,Integer cdtye,Integer ymm) {

        String tagManual = "{";

        String cdtyeTag="";
        String dzjymTag="";
        String ehmTag="";
        String dmTag="";
        String ymmTag = "";

        int flag=0;

        if(dm!=0){
            dmTag="\"dm\":"+dm;

        }
        if(ehm!=0){
            ehmTag="\"ehm\":"+ehm;

        }
        if(dzjym!=0){
            dzjymTag="\"dzjym\":"+dzjym;

        }
        if(cdtye!=0){
            cdtyeTag="\"cdtye\":"+cdtye;
        }
        if(ymm !=0){
            ymmTag = "\"ymm\":"+ymm;
        }



        if(!dmTag.equals("")){
            tagManual+=dmTag;
            flag=1;
        }
        if(flag==1 && (!ehmTag.equals("") || !dzjymTag.equals("") ||!cdtyeTag.equals("")) || !ymmTag.equals("")){
            tagManual+=",";
            flag=0;
        }
        if(!ehmTag.equals("") ){
            tagManual+=ehmTag;
            flag=1;
        }
        if(flag==1 && (!dzjymTag.equals("") ||!cdtyeTag.equals("")) ||!ymmTag.equals("")){
            tagManual+=",";
            flag=0;
        }
        if(!dzjymTag.equals("") ){
            tagManual+=dzjymTag;
            flag=1;
        }
        if(flag==1 && (!cdtyeTag.equals("") ||!ymmTag.equals(""))){
            tagManual+=",";
            flag=0;
        }
        if(!cdtyeTag.equals("") ){
            tagManual+=cdtyeTag;
            flag=1;
        }
        if(flag==1 && !ymmTag.equals("")){
            tagManual+=",";
        }
        if(!ymmTag.equals("")){
            tagManual+=ymmTag;
        }
        tagManual+="}";
        return tagManual;
    }

    /**
     * 将数据库中的JSON格式转换为对象格式
     * other : 0,
     * 'dm': 1,
     * 'ehm': 2,
     * 'dzjym': 3,
     * 'cdtye': 4,
     *

     * @return InsectType类型
     */
    public static InducePestNumType json2InsectTypeString(String tag) {

        int dm = 0;

        int ehm = 0;

        int dzjym = 0;

        int cdtye = 0;

        int ymm=0;



        int other = 0;
        if(tag == null ||"".equals(tag)){
            return new InducePestNumType();
        }

        JSONObject totalNum = JSON.parseObject(tag);
        if (totalNum.containsKey("1")) {
            dm += (Integer) totalNum.get("1");
        }
        if (totalNum.containsKey("2")) {
            ehm += (Integer) totalNum.get("2");
        }
        if (totalNum.containsKey("ehm")) {
            ehm += (Integer) totalNum.get("ehm");
        }
        if (totalNum.containsKey("3")) {
            dzjym += (Integer) totalNum.get("3");
        }
        if (totalNum.containsKey("dzjym")) {
            dzjym += (Integer) totalNum.get("dzjym");
        }

        if (totalNum.containsKey("4")) {
            cdtye += (Integer) totalNum.get("4");
        }
        if (totalNum.containsKey("cdtye")) {
            cdtye += (Integer) totalNum.get("cdtye");
        }

        if (totalNum.containsKey("0")) {
            other += (Integer) totalNum.get("0");
        }
        if (totalNum.containsKey("ymm")) {
            ymm += (Integer) totalNum.get("ymm");
        }



        return new InducePestNumType(dm, ehm, dzjym, cdtye, ymm,other);
    }

}
